package requests

import (
	"awesome-devops/applications/backend/modules/define"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"gitee.com/jjawesomejj/awesomehttp/system/httpContext"
	"reflect"
	"strconv"
	"strings"
)

type PageRequest struct {
	Page     int
	PageSize int
}

func parseInt(number string, defaultData int) int {
	res, err := strconv.Atoi(number)
	if err == nil {
		return res
	}
	return defaultData
}

func ResolveDefaultPageRequest(ctx *httpContext.HttpContext) PageRequest {
	page := 1
	pageSize := 20
	switch strings.ToUpper(ctx.Request.Method) {
	case awesomehttp.REQUEST_METHOD_POST:
		pageParams := ctx.PostOne("page")
		page = 1
		if pageParams != nil && reflect.TypeOf(pageParams).Kind() == reflect.Float64 {
			page = int(pageParams.(float64))
		}
		pageSizeParams := ctx.PostOne("page")
		if pageSizeParams != nil && reflect.TypeOf(pageSizeParams).Kind() == reflect.Float64 {
			pageSize = int(pageSizeParams.(float64))
		}
		break
	case awesomehttp.REQUEST_METHOD_GET:
		page = parseInt(ctx.Get("page", "1").(string), page)
		pageSize = parseInt(ctx.Get("page_size", "30").(string), pageSize)
		break
	}
	return PageRequest{
		Page:     page,
		PageSize: pageSize,
	}
}
func Input(context *httpContext.HttpContext, key string, reflectValue reflect.Kind, defaultValue ...interface{}) interface{} {
	var value interface{}
	switch strings.ToUpper(context.Request.Method) {
	case awesomehttp.REQUEST_METHOD_GET:
		value = context.Get(key, defaultValue...)
		break
	case awesomehttp.REQUEST_METHOD_POST:
		value = context.PostOne(key, defaultValue...)
		break
	}
	switch reflectValue {
	case reflect.Int:
		if value != nil && reflect.TypeOf(value).Kind() == reflect.String {
			tmp, err := strconv.Atoi(value.(string))
			if err == nil {
				value = tmp
			}
		}
		if value != nil && reflect.TypeOf(value).Kind() == reflect.Float64 {
			value = int(value.(float64))
		}
	}
	if value == nil {
		panic(define.NewRequestError(commonhelper.Format("key:[{}] request type is {}", key, reflectValue.String()), 100))
	}
	if reflect.ValueOf(value).Kind() == reflectValue {
		return value
	}
	panic(define.NewRequestError(commonhelper.Format("key:[{}] request type is {}", key, reflectValue.String()), 100))
}
